package dm.ast.model.gen;

import dm.ast.DmASTNode;
import dm.ast.DmSelect;
import dm.ast.DmUnionQuery;
import dm.ast.model.gen.factory.BaseModelFactory;
import dm.ast.model.gen.factory.ComplexityModel;
import dm.ast.model.gen.factory.UnionQueryModelFactory;
import org.omg.CORBA.PUBLIC_MEMBER;
import test.utility.Randomly;

public class UnionQueryGen extends ASTGenBase{

    BaseModelFactory baseModelF = new BaseModelFactory();
    public static boolean unionFlag = false;

    @Override
    public DmASTNode gen(int astLevel , int wid_t , int dep_t){
        DmUnionQuery dmUnionQuery = new DmUnionQuery();

        ComplexityModel model = UnionQueryModelFactory.unionModels(wid_t , dep_t);

        if(model.comps[0].wid_t > 0){
            SelectGen selGen = new SelectGen();
            selGen.setBaseModelF(baseModelF);
            if(baseModelF.testFlags[BaseModelFactory.FLAG_ORDER] || baseModelF.testFlags[BaseModelFactory.FLAG_LIMIT]){
                baseModelF.testFlags[BaseModelFactory.FLAG_ORDER] = false;
                baseModelF.testFlags[BaseModelFactory.FLAG_LIMIT] = false;
            }
            DmSelect select = (DmSelect) selGen.gen(astLevel,model.comps[0].wid_t,model.comps[0].dep_t);
            dmUnionQuery.addQuery(select);
            for (int i = 0; i < select.getSelectElements().elements.size(); i++) {
                dmUnionQuery.selTypes.add(select.getSelectElements().elements.get(i).reType);
            }
        }

        for (int i = 1; i < model.count; i++) {
            SelectGen selGen = new SelectGen();
            selGen.setBaseModelF(baseModelF);
            if(model.comps[i].wid_t > 0){
                if(dmUnionQuery.Selects.get(0).subClause[DmSelect.INDEX_WITH]!=null){
                    baseModelF.testFlags[BaseModelFactory.FLAG_WITH] = false;
                }
                if(baseModelF.testFlags[BaseModelFactory.FLAG_ORDER] || baseModelF.testFlags[BaseModelFactory.FLAG_LIMIT]){
                    baseModelF.testFlags[BaseModelFactory.FLAG_ORDER] = false;
                    baseModelF.testFlags[BaseModelFactory.FLAG_LIMIT] = false;
                }
                // 根据宽度、深度生成查询语句
                DmSelect select = (DmSelect)selGen.gen(astLevel , model.comps[i].wid_t , model.comps[i].dep_t,dmUnionQuery.selTypes.size(),dmUnionQuery.selTypes);
                dmUnionQuery.addQuery(select);

                //随机生成集合运算操作符
                dmUnionQuery.addUnionOps(genRanUnionOP());
            }
        }
        return dmUnionQuery;
    }

    public static int genRanUnionOP(){
        int op = 0;//默认是union
        //大部分是union
        if(Randomly.getBooleanWithRatherLowProbability()){
            op = Randomly.getInteger(1,4);
        }
        return op;
    }
}
